package com.atguigu.paymentdemo.service.impl;

import com.atguigu.paymentdemo.config.MyWXPayConfig;
import com.atguigu.paymentdemo.config.WxPayConfig;
import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.entity.Product;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.enums.wxpay.WxApiType;
import com.atguigu.paymentdemo.enums.wxpay.WxNotifyType;
import com.atguigu.paymentdemo.service.OrderInfoService;
import com.atguigu.paymentdemo.service.WxPayService;
import com.atguigu.paymentdemo.util.HttpClientUtils;
import com.atguigu.paymentdemo.util.OrderNoUtils;
import com.atguigu.paymentdemo.util.WXPayUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {


    @Resource
    private CloseableHttpClient wxPayClient;

    @Resource
    private OrderInfoService orderInfoService;

    @Autowired
    private MyWXPayConfig wxPayAppConfig;

    /**
     * 创建订单，调用native接口
     * @return code_url 和 订单号
     * @throws Exception
     */
    @Override
    public Map<String, Object> nativePay(OrderInfo orderInfo) throws Exception {

        //TODO 存入数据库


        log.info("调用统一下单api");
        //请求URL
            HttpPost httpPost = new HttpPost(wxPayAppConfig.getUnifiedOrderUrl());
            // 请求body参数
            Gson gson = new Gson();

            Map paramMap = new HashMap();
            paramMap.put("appid",wxPayAppConfig.getAppID());
            paramMap.put("mchid",wxPayAppConfig.getMchID());
            paramMap.put("description",orderInfo.getTitle());
            paramMap.put("out_trade_no",orderInfo.getOrderNo());
            paramMap.put("notify_url",wxPayAppConfig.getPayNotifyUrl());

            // 订单金额参数
            Map amountMap=new HashMap();
            amountMap.put("total",orderInfo.getTotalFee());
            amountMap.put("currency","CNY");
            paramMap.put("amount",amountMap);

            // 场景信息参数
            Map sceneInfo=new HashMap();
            sceneInfo.put("payer_client_ip","127.0.0.1");
            sceneInfo.put("device_id","");

            // 门店信息
            Map storeInfo = new HashMap();
            storeInfo.put("id","15459968");
            sceneInfo.put("store_info",storeInfo);

            Map h5Info = new HashMap();
            h5Info.put("type","Wap");
            sceneInfo.put("h5_info",h5Info);

            //场景信息添加到map
            paramMap.put("scene_info",sceneInfo);
            //将参数转换成jspn字符串
            String jsonParams= gson.toJson(paramMap);
            log.info("请求参数:"+jsonParams);



            StringEntity entity = new StringEntity(jsonParams,"utf-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");

            //完成签名并执行请求
            CloseableHttpResponse response = wxPayClient.execute(httpPost);

            try {
                String bodyAsString = EntityUtils.toString(response.getEntity());//响应体
                int statusCode = response.getStatusLine().getStatusCode();//响应状态码
                if (statusCode == 200) { //处理成功
                    log.info("成功,返回结果 = " + bodyAsString);
                } else if (statusCode == 204) { //处理成功，无返回Body
                    log.info("成功");
                } else {
                    log.info("Nataive下单失败,响应码 = " + statusCode+ ",返回结果 = " + bodyAsString);
                    throw new IOException("request failed");
                }
                //响应结果
                HashMap<String,String> resultMap = gson.fromJson(bodyAsString,HashMap.class);

                String h5_url = resultMap.get("h5_url");


                Map<String, Object> map = new HashMap<>();
                map.put("url",h5_url);
                map.put("orderNo",orderInfo.getOrderNo());

                return map;
            } finally {
                response.close();
            }


    }
}
